package com.controller.lib

import android.content.Context
import android.content.Intent
import android.media.AudioManager
import android.os.Environment
import android.text.TextUtils
import com.controller.lib.DmSdk
import com.controller.lib.activity.PlayerViewActivity
import com.controller.lib.activity.WallpaperImageActivity
import com.controller.lib.download.OKDownloadHelper
import com.controller.lib.download.OKDownloadHelper.DownloadListener

import com.controller.lib.upgrade.InstallHelper
import com.controller.lib.utils.EncryptUtils
import com.controller.lib.utils.FileUtils
import com.controller.lib.utils.FileUtils.Companion.deleteAllInDir
import com.controller.lib.utils.SystemUtils
import com.liulishuo.okdownload.DownloadTask
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch
import timber.log.Timber
import java.io.File
import java.util.Locale

/**
 *    @author : GeRui
 *    date   : 2025/6/6 16:04
 *    desc   : 管理控制属性的类
 *    version: 1.0
 */
class ControllerHelper private constructor(private val context: Context) {

  /**
   * 展示图片存放的目录
   */
  private val PICTURES_DIR =
    Environment.getExternalStorageDirectory().absolutePath + "/ShowPictures/"

  /**
   * 下载文件存放的目录
   */
  private val DOWNLODER_FILE_PATH =
    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).path + "/files/"

  /**
   * 下载文件存放的目录
   */
  private val DOWNLODER_MOVIES_FILE_PATH =
    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES).path

  private val EXTERNAL_DIR = "SHOWPICTURES"

  /**
   * 自定义系统广播
   * */
  private val CUSTOM_SYSTEM_COMMAND = "com.action.CONTROLLER_COMMAND"
  private val FILTER = arrayOf(".png")
  private val FILTER_INTERNAL = arrayOf(".png", ".jpg")
  private var internalDir: File? = null
  private var externalDir: File? = null

  private var audioManager: AudioManager? = null

  private var cachedDeviceSN: String? = null

  private var cachedWiredMac: String? = null

  private val coroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)

  init {
    audioManager = getAudioManager()
  }

  companion object {
    @Volatile
    private var internalInstance: ControllerHelper? = null

    val instance: ControllerHelper
      get() {
        if (internalInstance == null) {
          synchronized(ControllerHelper::class.java) {
            if (internalInstance == null) {
              internalInstance = ControllerHelper(DmSdk.getContext())
            }
          }
        }
        return internalInstance!!
      }
  }

  /**
   * 设置当前媒体音量.
   *
   * @param volume 音量
   */
  fun setStreamVolume(volume: Int) {
    Timber.d("setStreamVolume: $volume")
    audioManager!!.setStreamVolume(AudioManager.STREAM_MUSIC, volume, AudioManager.FLAG_PLAY_SOUND)
  }

  /**
   * 显示图片
   * */
  fun showPictures(wallpaperUrl: String,md5:String) {
    //是否直接加载图片，无需下载可注释掉下载逻辑
    CoroutineScope(Dispatchers.Main).launch {
      DmSdk.notifyDownLoadComplete(wallpaperUrl,Constants.SET_SYS_BACKGROUND)
      val intent = Intent(context, WallpaperImageActivity::class.java)
      intent.putExtra("image_url", wallpaperUrl)
      intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
      context.startActivity(intent)
    }
  }

  /**
   * 保存文件
   * */
  fun downLoaderFile(url: String,fileMd5:String) {
    val fileName =  url.substring(url.lastIndexOf("/") + 1)
    Timber.d("saveFile: $url, fileName: $fileName")
    OKDownloadHelper.getInstance().startDownload(url,DOWNLODER_FILE_PATH, fileName,fileMd5, object : DownloadListener {
      override fun onDownloadFinish(file: File?, task: DownloadTask?) {
        Timber.d("downLoaderFile: ${file?.absolutePath}")
        DmSdk.notifyDownLoadComplete(file?.path ?: "",Constants.SET_DOWNLOAD_FILE)
      }

      override fun onErrorEvent(task: DownloadTask?, exception: java.lang.Exception?) {
        Timber.e("downLoaderFile error: ${exception?.message}")
      }
    })

  }

  /**
   * 发送系统控制命令
   * */
  fun sendSystemCommands(command: String) {
    Timber.d("sendSystemCommands: $command")
    val intent = Intent(CUSTOM_SYSTEM_COMMAND)
    intent.setFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
    intent.addFlags(0x01000000)
    intent.putExtra("command", command)
    context.sendBroadcast(intent)
  }

  /**
   * 启动升级
   */
  fun upgradeApk(apkUrl: String, fileMd5: String) {
    val fileName =  EncryptUtils.encryptMD5ToString(apkUrl) + ".apk"
    OKDownloadHelper.getInstance().startDownload(apkUrl,DOWNLODER_FILE_PATH, fileName,fileMd5,  object : DownloadListener {
      override fun onDownloadFinish(file: File?, task: DownloadTask?) {
        Timber.d("upgradeApk: ${file?.path}")
        InstallHelper.installApkPackage(context, file?.path)
      }

      override fun onErrorEvent(task: DownloadTask?, exception: java.lang.Exception?) {
      }
    })

  }

  /**
   * 播放视频
   * */
  fun playerVideo(videoPath: String,fileMd5:String) {
    val fileName =  videoPath.substring(videoPath.lastIndexOf("/") + 1)
    Timber.d("saveFile: $videoPath, fileName: $fileName")
    OKDownloadHelper.getInstance().startDownload(videoPath,DOWNLODER_FILE_PATH, fileName,fileMd5, object : DownloadListener {
      override fun onDownloadFinish(file: File?, task: DownloadTask?) {
        Timber.d("downLoaderFile: ${file?.absolutePath}")
        DmSdk.notifyDownLoadComplete(file?.path ?: "",Constants.SET_DISTRIBUTE_VIDEOS)
        val intent = Intent(context, PlayerViewActivity::class.java)
        intent.putExtra("video_url", file?.path)
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        context.startActivity(intent)
      }

      override fun onErrorEvent(task: DownloadTask?, exception: java.lang.Exception?) {
      }
    })

  }

  /**
   * 构造AudioManager
   */
  fun getAudioManager(): AudioManager {
    return context.getSystemService(Context.AUDIO_SERVICE) as AudioManager
  }

  /**
   * 媒体音是否静音.
   *
   * @return 静音状态
   */
  fun isStreamMute(): Boolean {
    return audioManager!!.isStreamMute(AudioManager.STREAM_MUSIC)
  }

  private fun setStreamVolumeMute(mute: Boolean) {
    audioManager!!.setStreamMute(AudioManager.STREAM_MUSIC, mute)
  }

  /**
   * 获取当前媒体音量.
   */
  fun getStreamVolume(): Int {
    return audioManager!!.getStreamVolume(AudioManager.STREAM_MUSIC)
  }

  private val externalWallpaperDir: File
    get() {
      if (externalDir == null) {
        externalDir = File(
          Environment.getExternalStorageDirectory(),
          EXTERNAL_DIR
        )
      }
      return externalDir!!
    }

  private fun createExternalWallpaperDir(): Boolean {
    if (Environment.MEDIA_MOUNTED == Environment.getExternalStorageState()) {
      val file = externalWallpaperDir
      return FileUtils.createOrExistsDir(file)
    }
    return false
  }

  private fun createNoMediaFileInExternal() {
    val file = File(externalWallpaperDir, ".nomedia")
    FileUtils.createOrExistsFile(file)
  }

  /**
   * 获取设备SN.
   * 优先从SDK初始化传入的值获取，如果没有则自动读取并缓存
   */
  @Synchronized
  fun getDeviceSN(): String {
    if (cachedDeviceSN == null) {
      cachedDeviceSN = SystemUtils.getSerialNumber(DmSdk.getContext())
    }
    return cachedDeviceSN ?: ""
  }

  /**
   * 获取有线MAC地址.
   * 优先从SDK初始化传入的值获取，如果没有则自动读取并缓存
   */
  @Synchronized
  fun getMacAddress(): String {
    cachedWiredMac = SystemUtils.getEthMac()
    if(cachedWiredMac.isNullOrEmpty()) {
      cachedWiredMac = SystemUtils.getWlanMac()
    }
    Timber.d("获取设备Wired Mac: $cachedWiredMac")
    if(cachedWiredMac.isNullOrEmpty()) {
      cachedWiredMac = "00:00:00:00:00:00" // 默认值
    }
    return cachedWiredMac.toString()
  }


}

